package com.object.utils;


import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 15784
 */
public class FilterFieldsImpl
{
    private static final Logger log = LoggerFactory.getLogger(FilterFieldsImpl.class);

    /**
     * 通过实体类提前需要返回的字段
     *
     * @param clazz  类的class
     * @param t      类
     * @param fields 需要的字段
     * @param <T>    类
     * @return map
     * Author:Li
     */
    @SneakyThrows
    public static <T> Map<String, Object> filterFields(Class<T> clazz, T t, String... fields)
    {
        Map<String, Object> map = new HashMap<>();
        Field[] fields1 = clazz.getDeclaredFields();
        for (Field field : fields1)
        {
            field.setAccessible(true);
            String name = field.getName();
            Object object = field.get(t);
            map.put(name, object);
        }
        Map<String, Object> mapPut = new HashMap<>();
        for (String field : fields)
        {
            if (map.containsKey(field))
            {
                mapPut.put(field, map.get(field));
            }
            else
            {
                log.info(String.format("当前字段不存在:%s", field));
            }
        }
        return mapPut;
    }

    /**
     * 通过实体类提前需要返回的字段
     *
     * @param clazz  类的class
     * @param t      类集合
     * @param fields 需要的字段
     * @param <T>    类
     * @return map
     * Author:Li
     */
    @SneakyThrows
    public static <T> List<Map<String, Object>> filterFields(Class<T> clazz, List<T> t, String... fields)
    {

        //把我们需要的字段找出来
        Map<String, String> fieldsMap = Arrays.stream(fields).collect(Collectors.toMap(e -> e, e -> e));
        List<Field> fieldsArr = new ArrayList<>();
        Field[] fields1 = clazz.getDeclaredFields();
        for (Field field : fields1)
        {
            field.setAccessible(true);
            String name = field.getName();
            if (fieldsMap.containsKey(name))
            {
                fieldsArr.add(field);
            }
        }

        List<Map<String, Object>> list = new ArrayList<>();
        //提取字段和值
        for (T t1 : t)
        {
            Map<String, Object> map = new HashMap<>();
            for (Field field : fieldsArr)
            {
                Object object = field.get(t1);
                map.put(field.getName(), object);
            }
            list.add(map);
        }

        return list;
    }
}
